package ink.xiaobaibai.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import ink.xiaobaibai.interceptor.ParameterValidInterceptor;
import ink.xiaobaibai.parameterValid.ParameterValidManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.List;

/**
 * @description:
 * @author: 小白白
 * @create: 2021-05-23
 **/

@Configuration
@EnableSwagger2
public class WebConfig extends WebMvcConfigurationSupport {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private ParameterValidManager parameterValidManager;

    private ParameterValidInterceptor parameterValidInterceptor = new ParameterValidInterceptor();

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        this.parameterValidInterceptor.setParameterValidManager(this.parameterValidManager);
        registry.addInterceptor(this.parameterValidInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("classpath:/static/", "/error", "/login", "/user/login", "/wx-pay/callback", "/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }

    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        Jackson2ObjectMapperBuilder json = Jackson2ObjectMapperBuilder.json();
        json.applicationContext(this.applicationContext);
        json.serializationInclusion(JsonInclude.Include.NON_NULL);
        converters.removeIf(f -> f.getClass() == MappingJackson2HttpMessageConverter.class);
        converters.add(new MappingJackson2HttpMessageConverter(json.build()));
    }

}
